package com.joyveb.securitycheck.pkcs11.util;

import java.io.ByteArrayInputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.Security;
import java.security.cert.X509Certificate;
import java.util.Enumeration;

/**
 * Ukey test demo libgm3000_pkcs11××.so 是龙脉Ukey的调用库，其他厂商的Ukey需要替换该文件
 * 
 * @author yangqiju
 *	http://yangqiju.github.io/ssl-tls-ukey-pkcs11/
 */
public class UKeyTest {
	public static void main(String[] args) throws Exception {
		String filename = "libgm3000_pkcs11_64.so";
		String path = UKeyTest.class.getResource(filename).getFile();
		String pkcs11config = "library = " + path+ "\n name = longmaiSC\n";
		// + "slot = 0"; // force slot 0
		Provider longmai_Provider = new sun.security.pkcs11.SunPKCS11(
				new ByteArrayInputStream(pkcs11config.getBytes()));
		Security.addProvider(longmai_Provider);
		char[] pin = "12345678".toCharArray();//password
		KeyStore ks = KeyStore.getInstance("PKCS11","SunPKCS11-longmaiSC");//SunPKCS11 前缀必须有
		ks.load(null, pin);
		Enumeration<String> aliasesEnum = ks.aliases();
		while (aliasesEnum.hasMoreElements()) {
			String alias = (String) aliasesEnum.nextElement();
			System.out.println("Alias: " + alias);
			X509Certificate cert = (X509Certificate) ks.getCertificate(alias);//获得证书
			PrivateKey privateKey = (PrivateKey) ks.getKey(alias,null);
			System.out.println("Private key: " + privateKey);
		}

	}
}
